<template>
    <div class="load">
        <div>
            <!-- 表单 -->
            <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="120px">
                <el-form-item label="请选择时间" prop="yearTime">
                    <el-input v-model="ruleForm.yearTime" placeholder="请选择所教学生入学时间"></el-input>
                </el-form-item>
                <el-form-item label="请选择学校" prop="schoolName">
                    <el-select v-model="ruleForm.schoolName" placeholder="请选择学校信息">
                        <el-option v-for="item in school_name" :key="item.value" :label="item.label"
                            :value="item.label"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <!-- 文件上传 -->
            <el-upload class="upload-demo" drag :show-file-list="false" accept=".xlsx,.xls" @change="handleFileUpload">
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                    拖拽上传 或者 <em>点击上传</em>
                </div>
                <template #tip>
                    <div class="el-upload__tip">只能上传xlx文件</div>
                </template>
            </el-upload>
        </div>

        <!-- 显示数据 -->
        <!-- <div v-if="excelData.length > 0">
            <h3>处理后的 Excel 数据：</h3>
            <pre>{{ excelData }}</pre>
        </div> -->
    </div>
</template>

<script setup>
import { ref, reactive, toRefs } from "vue";
import * as XLSX from "xlsx";
import { UploadFilled } from "@element-plus/icons-vue";
const { proxy } = getCurrentInstance();
const { school_name } = proxy.useDict('school_name');
import { addIndicator } from "@/api/indicator/indicator";
const hasTriggered = ref(false); // 标志位，防止重复触发上传事件
// 页面传递数据
const { message } = defineProps(['message'])
const data = reactive({
    ruleForm: {
        yearTime: "",
        schoolName: ""
    },
    rules: {
        yearTime: [
            { required: true, message: "入学时间不能为空", trigger: "blur" },
        ],
        schoolName: [
            { required: true, message: "学校信息不能为空", trigger: "blur" },
        ]
    }
})
import { ElMessage } from 'element-plus'
const { ruleForm, rules } = toRefs(data);
const excelData = ref([]);

import { defineEmits } from 'vue';
const emit = defineEmits(['submit_success']);
// 文件上传处理函数
const handleFileUpload = async (file) => {
    // 检查学校信息和入学时间
    if (!ruleForm.value.yearTime || !ruleForm.value.schoolName) {
        proxy.$message.error("请先选择入学时间和学校信息！")
        return;
    } else {
        const schoolName = `学校：${ruleForm.value.schoolName}`;
        const gradeName = `年级：${new Date().getFullYear() - ruleForm.value.yearTime + 1}年级`;
        const schoolGrade = `${schoolName}，${gradeName}`; // 分组键
        if (schoolGrade in message) {
            ElMessage({
                type: 'error',
                message: '该年级已存在指标，请勿重复添加',
            });
            return;
        }
    }

    if (hasTriggered.value) return; // 如果已经触发过，就不再执行
    hasTriggered.value = true; // 设为已触发，防止重复执行

    const reader = new FileReader();
    reader.onload = (e) => {
        const data = e.target.result;
        const workbook = XLSX.read(data, { type: "binary" });

        // 获取第一个工作表
        const sheet = workbook.Sheets[workbook.SheetNames[0]];
        if (!sheet) {
            console.error("工作表为空！");
            return;
        }

        // 将工作表内容转换为 JSON 格式
        const jsonData = XLSX.utils.sheet_to_json(sheet);
        if (jsonData.length === 0) {
            console.error("读取到的数据为空！");
            return;
        }

        // 数据处理
        var res = jsonData.map((item) => {
            return {
                treeCode: item['指标id'].toString(),
                description: item['指标名称'],
                weight: item['指标权重']
            };
        });

        hanleDate(res); // 调用处理数据的函数
    };

    // 读取文件内容
    reader.readAsBinaryString(file.raw);
};

// 数据处理函数
function hanleDate(res) {
    const excelDataTemp = []; // 临时存储处理的数据

    res.forEach(item => {
        const list = item.treeCode.split('.');
        let level = 0; // 等级
        let category = '';
        let parentIndicatorId = '';
        const description = item.description;
        const treeCode = item.treeCode;
        const weight = item.weight;
        const len = list.length;

        if (len == 1) {
            level = 1;
            parentIndicatorId = null;
            category = serise(list[0]);
        } else if (len == 2) {
            level = 2;
            parentIndicatorId = list[0];
            category = serise(list[0]);
        } else {
            level = 3;
            parentIndicatorId = list[0] + '.' + list[1];
            category = serise(list[0]);
        }

        excelDataTemp.push({
            schoolID: ruleForm.value.schoolName, // 使用ruleForm中的schoolName
            gradeID: ruleForm.value.yearTime, // 使用ruleForm中的yearTime
            category: category,
            level: level,
            description: description,
            parentIndicatorId: parentIndicatorId,
            weight: weight,
            treeCode: treeCode
        });
    });

    // 使用 Promise.all 来确保所有异步请求完成后再进行后续操作
    const flagPromises = excelDataTemp.map(item => addIndicator(item).then(res => {
        if (res.code !== 200) {
            return false;
        }
        return true;
    }).catch(err => {
        return false;
    }));

    // 等待所有的请求完成
    Promise.all(flagPromises).then(results => {
        const allSuccess = results.every(result => result === true);
        if (allSuccess) {
            proxy.$message.success("指标导入成功！");
        } else {
            proxy.$message.error("指标导入失败！");
        }
        hasTriggered.value = false; // 操作完成后恢复触发状态
        // 子->父
        emit('submit_success');
    });
}

function serise(res) {
    var temp = ''
    switch (res) {
        case '1': temp = "德育"
            break;
        case '2': temp = "智育"
            break;
        case '3': temp = "体育"
            break;
        case '4': temp = "美育"
            break;
        case '5': temp = "劳育"
            break;
    }

    return temp
}
</script>

<style scoped lang="less">
.load {
    padding: 20px;
    text-align: center;
}

.el-upload__text {
    margin: 20px 0;
}

pre {
    text-align: left;
    white-space: pre-wrap;
    word-wrap: break-word;
}
</style>